﻿using System;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;

using MiniSched.Orm.Abstractions;

namespace MiniSched.Orm.Initialization {

    public class MiniSchedContextInitializer {

        internal DatabaseAbstraction Database {
            get {
                if (null == _Database) _Database = DatabaseAbstraction.Default;
                return _Database;
            }
            set {
                if (null == value) throw new ArgumentNullException("Database");
                _Database = value;
            }
        }
        private DatabaseAbstraction _Database;

        public MiniSchedContextFactory ContextFactory {
            get {
                if (null == _ContextFactory) _ContextFactory = new MiniSchedContextFactory();
                return _ContextFactory;
            }
            set {
                if (null == value) throw new ArgumentNullException("ContextFactory");
                _ContextFactory = value;
            }
        }
        private MiniSchedContextFactory _ContextFactory;

        public IDatabaseInitializer<MiniSchedContext> DatabaseInitializer {
            get { return _DatabaseInitializer; }
            set { _DatabaseInitializer = value; }
        }
        private IDatabaseInitializer<MiniSchedContext> _DatabaseInitializer;

        public MiniSchedSeeder<MiniSchedContext> Seeder {
            get { return _Seeder; }
            set { _Seeder = value; }
        }
        private MiniSchedSeeder<MiniSchedContext> _Seeder = new MiniSchedSeeder<MiniSchedContext>();

        public void InitializeContext() {

            Database.SetInitializer(DatabaseInitializer);

            using (var context = ContextFactory.CreateContext()) {
                
                var database = context.Database;
                if (database == null) throw new InvalidOperationException("The database cannot be null.");                

                if (database.Exists() == false) {
                    database.Create();

                    var seeder = Seeder;
                    if (seeder != null) {
                        seeder.Seed(context);
                    }
                }                
            }
        }
    }
}
